package com.yanqu.road.server.manager.strongholdwar;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.stronghold.*;
import com.yanqu.road.entity.activity.stronghold.config.StrongholdEliminateReportDetail;
import com.yanqu.road.entity.activity.stronghold.config.StrongholdWildConfig;
import com.yanqu.road.entity.log.stronghold.*;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.rank.stronghold.CrossActivityUnionRank;
import com.yanqu.road.entity.union.UnionBaseInfo;
import com.yanqu.road.logic.bussiness.player.activity.CrossStrongholdBusiness;
import com.yanqu.road.logic.bussiness.player.activity.StrongholdLogBusiness;
import com.yanqu.road.logic.bussiness.player.activity.UserStrongholdBusiness;
import com.yanqu.road.pb.activity.StrongholdWarProto;
import com.yanqu.road.server.manager.union.activitygroup.Cross2UnionActivityGroupMgr;
import com.yanqu.road.server.protocol.GameErrorCode;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class StrongholdActivityModel {
    private int groupId;
    private int activityId;
    private Map<Integer, StrongholdWildModel> wildModelMap = new ConcurrentHashMap<>();

    private AtomicInteger maxBoxId = new AtomicInteger(0);
    private AtomicInteger maxEventId = new AtomicInteger(0);

    private Map<Integer, StrongholdWildBox> allBoxMap = new ConcurrentHashMap<>();

    private List<StrongholdWildUserData> allWildUserDataList = new ArrayList<>();

    private Map<Integer, CrossStrongholdEliminateModel> roundEliminateModelMap = new ConcurrentHashMap<>();

    private final static Map<Long, Object> USER_LOCK_MAP = new ConcurrentHashMap<>();


    /**
     * 存储淘汰赛联盟积分
     */
    private Map<String, StrongholdEliminateUnionScore> unionScoreMap = new ConcurrentHashMap<>();

    /**
     * 玩家每回合的伤害值
     */
    private Map<Integer, Map<Long, CrossStrongholdUserRoungDamage>> userRoundDamageMap = new ConcurrentHashMap<>();

    public static Object getUserLock(long userId) {
        if (!USER_LOCK_MAP.containsKey(userId)) {
            synchronized (USER_LOCK_MAP) {
                if (!USER_LOCK_MAP.containsKey(userId)) {
                    USER_LOCK_MAP.put(userId, new Object());
                }
            }
        }
        return USER_LOCK_MAP.get(userId);
    }


    public StrongholdActivityModel(int activityId, int groupId) {
        this.activityId = activityId;
        this.groupId = groupId;
    }

    public void reload(List<StrongholdWildUserData> allWildUserDataListTemp, Map<String, StrongholdEliminateUnionScore> unionScoreMapTemp, Map<Integer, Map<Long, CrossStrongholdUserRoungDamage>> userRoundDamageMapTemp, List<CrossStrongholdEliminateUnion> eliminateUnionList, List<CrossStrongholdEliminateDefendPatrons> defendPatronsList, List<CrossStrongholdEliminateDamage> eliminateDamageList) {
        for (StrongholdWildUserData strongholdWildUserData : allWildUserDataListTemp) {
            int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, strongholdWildUserData.getUserId());
            if (groupId == this.groupId) {
                allWildUserDataList.add(strongholdWildUserData);
            }
        }

        for (StrongholdEliminateUnionScore eliminateUnionScore : unionScoreMapTemp.values()) {
            int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, eliminateUnionScore.getUnionId());
            if (groupId == this.getGroupId()) {
                unionScoreMap.put(eliminateUnionScore.getUnionId(), eliminateUnionScore);
            }
        }

        for (Map<Long, CrossStrongholdUserRoungDamage> roungDamageMap : userRoundDamageMapTemp.values()) {
            for (CrossStrongholdUserRoungDamage userRoundDamage : roungDamageMap.values()) {
                int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userRoundDamage.getUnionId());
                if (groupId == this.getGroupId()) {
                    Map<Long, CrossStrongholdUserRoungDamage> userIdMap = userRoundDamageMap.get(userRoundDamage.getRound());
                    if (null == userIdMap){
                        userIdMap = new ConcurrentHashMap<>();
                        userRoundDamageMap.put(userRoundDamage.getRound(), userIdMap);
                    }
                    userIdMap.put(userRoundDamage.getUserId(), userRoundDamage);
                }
            }
        }

        allBoxMap = UserStrongholdBusiness.getWildBox(activityId, groupId);
        for (StrongholdWildBox box : allBoxMap.values()) {
            if (box.getBoxId() > maxBoxId.intValue()) {
                maxBoxId = new AtomicInteger(box.getBoxId());
            }
        }
        maxEventId = StrongholdLogBusiness.getMaxEventId(activityId, groupId);
        wildModelMap = new ConcurrentHashMap<>(2);
        Map<Integer, StrongholdHouseData> houseDataMap = UserStrongholdBusiness.getStrongholdHouseData(activityId, groupId);
        List<StrongholdWildConfig> allHouseInfo = CrossStrongholdActivityMgr.getAllHouseInfo(activityId);
        for (StrongholdWildConfig wildConfig : allHouseInfo) {
            initModel(wildConfig.getId(), houseDataMap);
        }
        roundEliminateModelMap = new ConcurrentHashMap<>();
        //初始化淘汰赛
        initEliminateModel(eliminateUnionList, defendPatronsList, eliminateDamageList);
    }

//    private void reload() {
//        allBoxMap = UserStrongholdBusiness.getWildBox(activityId, groupId);
//        for (StrongholdWildBox box : allBoxMap.values()) {
//            if (box.getBoxId() > maxBoxId.intValue()) {
//                maxBoxId = new AtomicInteger(box.getBoxId());
//            }
//        }
//        maxEventId = StrongholdLogBusiness.getMaxEventId(activityId, groupId);
//        allWildUserDataList = UserStrongholdBusiness.getAllStrongholdWildUserData(activityId);
//        wildModelMap = new ConcurrentHashMap<>(2);
//        Map<Integer, StrongholdHouseData> houseDataMap = UserStrongholdBusiness.getStrongholdHouseData(activityId);
//        List<StrongholdWildConfig> allHouseInfo = CrossStrongholdActivityMgr.getAllHouseInfo(activityId);
//        for (StrongholdWildConfig wildConfig : allHouseInfo) {
//            initModel(wildConfig.getId(), houseDataMap);
//        }
//        unionScoreMap = CrossStrongholdBusiness.getStrongholdEliminateUnionScoreMap(activityId);
//        roundEliminateModelMap = new ConcurrentHashMap<>();
//        //初始化淘汰赛
//        initEliminateModel();
//
//        userRoundDamageMap = CrossStrongholdBusiness.getCrossUserRoundDamage(activityId);
//    }

    /**
     * 初始化淘汰赛
     */
    private void initEliminateModel(List<CrossStrongholdEliminateUnion> tempEliminateUnionList, List<CrossStrongholdEliminateDefendPatrons> tempDefendPatronsList, List<CrossStrongholdEliminateDamage> tempEliminateDamageList) {
        Map<Integer, Map<Integer, CrossStrongholdEliminateUnion>> roundEliminateUnionMap = new HashMap<>();
        Map<Integer, Map<String, List<CrossStrongholdEliminateDefendPatrons>>> eliminatePatrons = new HashMap<>();
        Map<Integer, Map<String, Map<Long, Map<String, CrossStrongholdEliminateDamage>>>> roundDamageRecordMap = new HashMap<>();
        for (CrossStrongholdEliminateUnion union : tempEliminateUnionList) {
            int unionGroupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, union.getUnionUid());
            if (unionGroupId != this.groupId) {
                continue;
            }
            int round = union.getRound();
            Map<Integer, CrossStrongholdEliminateUnion> unionMap = roundEliminateUnionMap.get(round);
            if (unionMap == null) {
                unionMap = new ConcurrentHashMap<>();
                roundEliminateUnionMap.put(round, unionMap);
            }
            unionMap.put(union.getId(), union);
        }
        for (CrossStrongholdEliminateDefendPatrons crossStrongholdEliminateDefendPatrons : tempDefendPatronsList) {
            int unionGroupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, crossStrongholdEliminateDefendPatrons.getUnionUid());
            if (unionGroupId != this.groupId) {
                continue;
            }
            Map<String, List<CrossStrongholdEliminateDefendPatrons>> listMap = eliminatePatrons.get(crossStrongholdEliminateDefendPatrons.getRound());
            if (listMap == null) {
                listMap = new ConcurrentHashMap<>();
                eliminatePatrons.put(crossStrongholdEliminateDefendPatrons.getRound(), listMap);
            }
            List<CrossStrongholdEliminateDefendPatrons> defendPatronsList = listMap.get(crossStrongholdEliminateDefendPatrons.getUnionUid());
            if (defendPatronsList == null) {
                defendPatronsList = new ArrayList<>();
                listMap.put(crossStrongholdEliminateDefendPatrons.getUnionUid(), defendPatronsList);
            }
            defendPatronsList.add(crossStrongholdEliminateDefendPatrons);
        }
        for (CrossStrongholdEliminateDamage damageRecord : tempEliminateDamageList) {
            String unionUid = damageRecord.getUnionUid();
            int unionGroupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, unionUid);
            if (unionGroupId != this.groupId) {
                continue;
            }
            int round = damageRecord.getRound();
            Map<String, Map<Long, Map<String, CrossStrongholdEliminateDamage>>> damageRecordMap = roundDamageRecordMap.get(round);
            if (null == damageRecordMap) {
                damageRecordMap = new ConcurrentHashMap<>();
                roundDamageRecordMap.put(round, damageRecordMap);
            }

            Map<Long, Map<String, CrossStrongholdEliminateDamage>> attackUserMap = damageRecordMap.get(unionUid);
            if (attackUserMap == null) {
                attackUserMap = new ConcurrentHashMap<>(16);
                damageRecordMap.put(unionUid, attackUserMap);
            }
            Map<String, CrossStrongholdEliminateDamage> enemyServerMap = attackUserMap.get(damageRecord.getUserId());
            if (enemyServerMap == null) {
                enemyServerMap = new ConcurrentHashMap<>();
                attackUserMap.put(damageRecord.getUserId(), enemyServerMap);
            }
            enemyServerMap.put(damageRecord.getEnemyUnionUid(), damageRecord);
        }
//        Map<Integer, Map<Integer, CrossStrongholdEliminateUnion>> roundEliminateUnionMap = CrossStrongholdBusiness.getEliminateUnion(activityId);
//        Map<Integer, Map<String, List<CrossStrongholdEliminateDefendPatrons>>> eliminatePatrons = CrossStrongholdBusiness.getEliminatePatrons(activityId);
        for (Map.Entry<Integer, Map<Integer, CrossStrongholdEliminateUnion>> entry : roundEliminateUnionMap.entrySet()) {
            Integer round = entry.getKey();
            Map<Integer, CrossStrongholdEliminateUnion> unionMap = entry.getValue();
            Map<String, List<CrossStrongholdEliminateDefendPatrons>> patronsMap = eliminatePatrons.get(round);
            for (CrossStrongholdEliminateUnion union : unionMap.values()) {
                if (patronsMap != null) {
                    List<CrossStrongholdEliminateDefendPatrons> defendPatronsList = patronsMap.get(union.getUnionUid());
                    if (defendPatronsList != null) {
                        union.setDefendPatronsList(defendPatronsList);
                    }
                }
            }
            Map<String, Map<Long, Map<String, CrossStrongholdEliminateDamage>>> damageRecordMap = roundDamageRecordMap.getOrDefault(round, new ConcurrentHashMap<>());
            roundEliminateModelMap.put(round, new CrossStrongholdEliminateModel(this, activityId, round, unionMap, damageRecordMap));
        }
    }

    public StrongholdWildUserData getPatrons(long serverId, long userId) {
        for (StrongholdWildUserData userData : allWildUserDataList) {
            if (userData.getServerId() == serverId && userData.getUserId() == userId) {
                return userData;
            }
        }
        return null;
    }

    /**
     * 派遣
     *
     * @param wildId   野外据点id
     * @param serverId 区服id
     * @param userId   玩家id
     * @param patrons  门客信息
     */
    public int dispatchPatrons(int wildId, long serverId, long userId, UserBaseInfo userBaseInfo, UserPatrons patrons) {
        synchronized (allWildUserDataList) {
            StrongholdWildModel model = getWildModel(wildId);
            StrongholdWildUserData wildUserData = getPatrons(serverId, userId);
            if (wildUserData != null && wildUserData.getPatrons().getCurrentBlood().compareTo(BigInteger.ZERO) > 0 && wildUserData.getWildId() > 0) {
                //已经派遣且未被击败
                return GameErrorCode.E_STRONGHOLD_DISPATCH_ALREADY;
            }
            if (wildUserData == null) {
                if (model == null) {
                    CrossStrongholdMgr.getLogger().error("userId {}, wildId {}", userId, wildId);
                    return GameErrorCode.E_HUA_SHI_GANG_POINT_ERROR;
                }
                wildUserData = new StrongholdWildUserData();
                wildUserData.setUserId(userId);
                wildUserData.setServerId(serverId);
                wildUserData.setActivityId(activityId);
                wildUserData.setInsertOption();
                allWildUserDataList.add(wildUserData);
            }
            wildUserData.setRewardPoints(CrossStrongholdActivityMgr.getInitRewardPoint(activityId));
            wildUserData.setUserBaseInfo(userBaseInfo);
            wildUserData.setPatrons(patrons);

            if (wildId != wildUserData.getWildId() && wildId != 0) {
                StrongholdWildModel oldModel = getWildModel(wildUserData.getWildId());
                if (oldModel != null) {
                    oldModel.goOut(serverId, userId);
                }
                model.userEnter(wildUserData);
            }
        }
        return 0;
    }

    public int move(int nextWildId, long serverId, long userId) {
        synchronized (getUserLock(userId)) {
            StrongholdWildUserData wildPatrons = getPatrons(serverId, userId);
            if (wildPatrons == null) {
                return GameErrorCode.E_STRONGHOLD_PATRONS_BEEN_KILLED;
            }
            if (wildPatrons.getWildId() == nextWildId) {
                return GameErrorCode.E_STRONGHOLD_MOVE_SAME_WILD;
            }
            if (wildPatrons.getPatrons().getCurrentBlood().compareTo(BigInteger.ZERO) <= 0) {
                return GameErrorCode.E_STRONGHOLD_PATRONS_BEEN_KILLED;
            }
            int oldWildId = wildPatrons.getWildId();
            if (oldWildId > 0) {
                StrongholdWildModel oldModel = getWildModel(oldWildId);
                oldModel.goOut(serverId, userId);
            }
            StrongholdWildModel nextModel = getWildModel(nextWildId);
            nextModel.userEnter(wildPatrons);
            return 0;
        }
    }

    /**
     * 搜索
     *
     * @param serverId 区服id
     * @param userId   玩家id
     */
    public StrongholdWarProto.CrossStrongholdSearchRespMsg.Builder search(long serverId, long userId) {
        synchronized (getUserLock(userId)) {
            StrongholdWildUserData wildUserData = getPatrons(serverId, userId);
            int wildId = wildUserData.getWildId();
            StrongholdWildModel model = getWildModel(wildId);
            return model.search(serverId, userId);
        }
    }

    public StrongholdWarProto.CrossDealStrongholdEventResp.Builder dealEvent(long serverId, long userId, boolean isDeal) {
        synchronized (getUserLock(userId)) {
            StrongholdWildUserData wildUserData = getPatrons(serverId, userId);
            if (wildUserData == null || wildUserData.getPatrons().getCurrentBlood().compareTo(BigInteger.ZERO) <= 0) {
                // 未派遣或已被击败
                StrongholdWarProto.CrossDealStrongholdEventResp.Builder resp = StrongholdWarProto.CrossDealStrongholdEventResp.newBuilder();
                resp.setRet(GameErrorCode.E_STRONGHOLD_PATRONS_BEEN_KILLED);
                resp.setDeal(isDeal);
                return resp;
            }
            int wildId = wildUserData.getWildId();
            StrongholdWildModel model = getWildModel(wildId);
            return model.dealEvent(serverId, userId, isDeal);
        }
    }

    private StrongholdWildModel getWildModel(int wildId) {
        return wildModelMap.get(wildId);
    }

    public void checkAndRefreshBox() {
        for (StrongholdWildModel model : wildModelMap.values()) {
            model.checkAndRefreshBox();
        }
    }

    public void refreshAddBox(List<StrongholdWildBox> boxList) {
        for (StrongholdWildBox box : boxList) {
            allBoxMap.put(box.getBoxId(), box);
        }
    }

    public int getNextBoxId() {
        return maxBoxId.incrementAndGet();
    }

    public int nextEventId() {
        return maxEventId.incrementAndGet();
    }

    public List<StrongholdWarProto.StrongholdFightStatusTempMsg.Builder> getWildListData() {
        List<StrongholdWarProto.StrongholdFightStatusTempMsg.Builder> msgList = new ArrayList<>();
        for (StrongholdWildModel model : wildModelMap.values()) {
            StrongholdWarProto.StrongholdFightStatusTempMsg.Builder modelMsg = model.getStatusMsg();
            msgList.add(modelMsg);
        }
        return msgList;
    }

    private void initModel(int wildId, Map<Integer, StrongholdHouseData> houseDataMap) {
        List<StrongholdWildUserData> houseUserList = new ArrayList<>();
        for (StrongholdWildUserData userData : allWildUserDataList) {
            if (userData.getWildId() == wildId) {
                houseUserList.add(userData);
            }
        }
        StrongholdHouseData houseData = houseDataMap.get(wildId);
        StrongholdWildModel model = new StrongholdWildModel(this, activityId, wildId, houseData, houseUserList);
        wildModelMap.put(wildId, model);
    }


    public boolean save() {

        for (StrongholdWildModel model : new ArrayList<>(wildModelMap.values())) {
            model.save();
        }
        for (StrongholdWildBox box : new ArrayList<>(allBoxMap.values())) {
            if (box.isInsertOption()) {
                UserStrongholdBusiness.addBox(box);
            } else if (box.isUpdateOption()) {
                UserStrongholdBusiness.updateBox(box);
            }
        }
        for (StrongholdWildUserData data : new ArrayList<>(allWildUserDataList)) {
            if (data.isInsertOption()) {
                UserStrongholdBusiness.addWildUser(data);
            } else if (data.isUpdateOption()) {
                UserStrongholdBusiness.updateWildUser(data);
            }
        }

        for (CrossStrongholdEliminateModel eliminateModel : new ArrayList<>(roundEliminateModelMap.values())) {
            eliminateModel.save();
        }

        for (StrongholdEliminateUnionScore unionScore : new ArrayList<>(unionScoreMap.values())) {
            if (unionScore.isInsertOption()) {
                CrossStrongholdBusiness.addStrongholdEliminateUnionScore(unionScore);
            } else if (unionScore.isUpdateOption()) {
                CrossStrongholdBusiness.updateStrongholdEliminateUnionScore(unionScore);
            }
        }

        for (Map<Long, CrossStrongholdUserRoungDamage> damageMap : new ArrayList<>(userRoundDamageMap.values())) {
            for (CrossStrongholdUserRoungDamage damage : new ArrayList<>(damageMap.values())) {
                if (damage.isInsertOption()) {
                    CrossStrongholdBusiness.addUserRoundDamage(damage);
                } else if (damage.isUpdateOption()) {
                    CrossStrongholdBusiness.updateUserRoundDamage(damage);
                }
            }
        }
        return true;
    }

    public void checkAndResetUnionScore() {

        int round = CrossStrongholdActivityMgr.getCurEmilinateRound(activityId);
        if (round == 0) {
            return;
        }
        for (StrongholdEliminateUnionScore unionScore : unionScoreMap.values()) {
            if (unionScore.getResetScoreRound() < round) {
                BigInteger curRoundScore = unionScore.getCurRoundScore();
                unionScore.setCurRoundScore(BigInteger.ZERO);
                unionScore.setHistoryScore(unionScore.getHistoryScore().add(curRoundScore));
                unionScore.setHistoryScore(new BigDecimal(unionScore.getHistoryScore()).multiply(new BigDecimal(CrossStrongholdActivityMgr.getUnionScoreInherit(activityId))).divide(new BigDecimal("1000"), 0, BigDecimal.ROUND_UP).toBigInteger());
                unionScore.setResetScoreRound(round);
                changeEliminateScore(unionScore.getUnionId(), unionScore.getUnionBaseInfo(), BigInteger.ZERO, BigInteger.ONE, BigInteger.ONE);
            }
        }
    }

    public StrongholdWildBox getBox(Integer boxId) {
        StrongholdWildBox box = allBoxMap.get(boxId);
        return box;
    }

    public void updateUnionBase(String unionId, UnionBaseInfo unionBaseInfo){
        CrossStrongholdEliminateModel eliminateModel = getCrossStrongholdEliminateModel();
        if (eliminateModel == null) {
            return;
        }
        eliminateModel.updateEliminateUnion(unionId, unionBaseInfo);
    }


    /**
     * 先上传据点信息
     *
     * @param serverId
     * @param eliminateUnions
     */
    public void uploadUnionBase(long serverId, List<CrossStrongholdEliminateUnion> eliminateUnions) {
        if (CrossStrongholdActivityMgr.isEliminateTime(activityId)) {
            return;
        }
        if (!CrossStrongholdActivityMgr.isRestTime(activityId)) {
            return;
        }
        int curEmilinateRound = CrossStrongholdActivityMgr.getUploadEliminateRound(activityId);
        synchronized (roundEliminateModelMap) {
            CrossStrongholdEliminateModel eliminateModel = roundEliminateModelMap.get(curEmilinateRound);
            if (eliminateModel == null) {
                eliminateModel = new CrossStrongholdEliminateModel(this, activityId, curEmilinateRound, new ConcurrentHashMap<>(), new ConcurrentHashMap<>());
                roundEliminateModelMap.put(curEmilinateRound, eliminateModel);
            }
            eliminateModel.uploadUnionBase(serverId, eliminateUnions);
        }
    }


    public StrongholdWarProto.StrongholdDataResp.Builder getWildData(StrongholdWildUserData userData) {
        StrongholdWildModel model = wildModelMap.get(userData.getWildId());
        return model.getWildData(userData);
    }

    public StrongholdOpenBoxResult openBox(long serverId, long userId, int boxId) {
        StrongholdWildUserData wildUserData = getPatrons(serverId, userId);
        if (wildUserData == null) {
            return new StrongholdOpenBoxResult(GameErrorCode.E_STRONGHOLD_PATRONS_BEEN_KILLED);
        }
        int wildId = wildUserData.getWildId();
        StrongholdWildModel wildModel = getWildModel(wildId);
        return wildModel.openBox(wildUserData, boxId);
    }


    public List<StrongholdWildBox> getBoxList(List<Integer> boxList) {
        List<StrongholdWildBox> list = new ArrayList<>();
        for (Integer boxId : boxList) {
            if (boxId == 0) {
                StrongholdWildBox box = new StrongholdWildBox();
                box.setGroupId(groupId);
                box.setBoxId(0);
                list.add(box);
            } else {
                StrongholdWildBox box = allBoxMap.get(boxId);
                if (box != null && box.getOpenTime() == 0) {
                    list.add(box);
                }
            }
        }
        return list;
    }


    public int getUserBoxSize(List<Integer> boxList) {
        int num = 0;
        for (Integer boxId : boxList) {
            StrongholdWildBox box = allBoxMap.get(boxId);
            if (box != null && box.getOpenTime() == 0) {
                num++;
            }
        }
        return num;
    }


    public List<StrongholdWildBox> getBoxByWildId(int wildId) {
        List<StrongholdWildBox> list = new ArrayList<>();
        for (StrongholdWildBox box : allBoxMap.values()) {
            if (box.getWildId() == wildId && box.getUserId() == 0) {
                list.add(box);
            }
        }
        return list;
    }

    public CrossStrongholdEliminateUnion chooseChallengeUnion(int id) {
        CrossStrongholdEliminateModel eliminateModel = getCrossStrongholdEliminateModel();
        return eliminateModel.getUnionById(id);
    }

    public List<CrossStrongholdEliminateUnion> getEliminateUnionList() {
        CrossStrongholdEliminateModel eliminateModel = getCrossStrongholdEliminateModel();
        if (eliminateModel == null) {
            return new ArrayList<>();
        }
        return eliminateModel.getEliminateUnionList();
    }

    public CrossStrongholdEliminateModel getCrossStrongholdEliminateModel() {
        int round = CrossStrongholdActivityMgr.getCurEmilinateRound(activityId);
        return roundEliminateModelMap.get(round);
    }

    public AttackUnionResult attack(long userId, UserBaseInfo userBaseInfo, int patronsId, BigInteger damage, int id) {
        CrossStrongholdEliminateModel eliminateModel = getCrossStrongholdEliminateModel();
        return eliminateModel.attack(userId, userBaseInfo, patronsId, damage, id);
    }

    public Map<String, StrongholdEliminateReport> getEliminateReport(int id, int type) {
        CrossStrongholdEliminateModel eliminateModel = getCrossStrongholdEliminateModel();
        return eliminateModel.getEliminateReport(id, type);
    }

    public List<StrongholdEliminateReportDetail> getEliminateReportDetail(int id, int type, int id2) {
        CrossStrongholdEliminateModel eliminateModel = getCrossStrongholdEliminateModel();
        if (eliminateModel == null) {
            return new ArrayList<>();
        }
        return eliminateModel.getEliminateReportDetail(id, type, id2);
    }


    public void changeEliminateScore(String unionUid, UnionBaseInfo unionBaseInfo, BigInteger totalDamage, BigInteger curBlood, BigInteger totalBlood) {
        synchronized (unionScoreMap) {
            StrongholdEliminateUnionScore unionScore = unionScoreMap.get(unionUid);
            if (unionScore == null) {
                unionScore = new StrongholdEliminateUnionScore();
                unionScore.setActivityId(activityId);
                unionScore.setUnionId(unionUid);
                unionScore.setResetScoreRound(CrossStrongholdActivityMgr.getCurEmilinateRound(activityId));
                unionScore.setInsertOption();
                unionScoreMap.put(unionUid, unionScore);
            }
            unionScore.setUnionBaseInfo(unionBaseInfo);
            String[] param = CrossStrongholdActivityMgr.getSocreParam(activityId);
            BigDecimal petcent = new BigDecimal(curBlood).divide(new BigDecimal(totalBlood), 10, RoundingMode.HALF_UP);
            BigDecimal param1 = petcent.multiply(new BigDecimal(param[0])).divide(new BigDecimal("1000"), 10, RoundingMode.HALF_UP);
            BigDecimal curScore = new BigDecimal(totalDamage).multiply(BigDecimal.ONE.add(param1)).setScale(0, BigDecimal.ROUND_UP);
            unionScore.setCurRoundScore(curScore.toBigInteger());

            BigInteger totalValue = unionScore.getHistoryScore().add(unionScore.getCurRoundScore());
            if (totalValue.compareTo(BigInteger.ZERO) > 0) {
                CrossActivityUnionRank unionRank = new CrossActivityUnionRank();
                unionRank.setActivityId(activityId);
                unionRank.setConditionType(CrossStrongholdActivityMgr.CONDITION_TYPE_ELIMINATE_UNION);
                unionRank.setLastUpdateTime(System.currentTimeMillis());
                unionRank.setServerId(unionBaseInfo.getServerId());
                unionRank.setUnionBaseInfo(unionBaseInfo);
                unionRank.setUnionUid(unionUid);
                unionRank.setValue(totalValue);
                CrossStrongholdRankMgr.changeStrongholdUnionRank(activityId, CrossStrongholdActivityMgr.CONDITION_TYPE_ELIMINATE_UNION, unionRank, false);
            }
        }
    }

    public MammonHelpResult mammonHelp(long userId, UserBaseInfo userBaseInfo, int type, int mammonType, List<Integer> idList, BigInteger totalDamage, int attackTimes) {
        CrossStrongholdEliminateModel eliminateModel = getCrossStrongholdEliminateModel();
        return eliminateModel.mammonHelp(userId, userBaseInfo, type, mammonType, idList, totalDamage, attackTimes);
    }

    public void addUserRoungDamage(int round, CrossStrongholdEliminateUnion  eliminateUnion, long userId, BigInteger addDamage, UserBaseInfo userBaseInfo) {
        synchronized (userRoundDamageMap) {
            if (eliminateUnion == null) {
                return;
            }
            if (eliminateUnion.getCurBlood().compareTo(BigInteger.ZERO) <= 0) {
                return;
            }
            String unionId = eliminateUnion.getUnionUid();
            Map<Long, CrossStrongholdUserRoungDamage> damageMap = userRoundDamageMap.get(round);
            if (damageMap == null) {
                damageMap = new ConcurrentHashMap<>();
                userRoundDamageMap.put(round, damageMap);
            }
            CrossStrongholdUserRoungDamage damage = damageMap.get(userId);
            if (damage == null) {
                damage = new CrossStrongholdUserRoungDamage();
                damage.setActivityId(activityId);
                damage.setRound(round);
                damage.setUnionId(unionId);
                damage.setDamage(BigInteger.ZERO);
                damage.setUserId(userId);
                damage.setInsertOption();
                damageMap.put(userId, damage);
            }
            damage.setUserBaseInfo(userBaseInfo);
            damage.setDamage(damage.getDamage().add(addDamage));
        }
    }

    public Map<Integer, List<CrossStrongholdUserRoungDamage>> getUnionMemberDamageMap(String unionId) {
        Map<Integer, List<CrossStrongholdUserRoungDamage>> tempMap = new HashMap<>();
        for (Map.Entry<Integer, Map<Long, CrossStrongholdUserRoungDamage>> entry : userRoundDamageMap.entrySet()) {
            Integer round = entry.getKey();
            List<CrossStrongholdUserRoungDamage> list = new ArrayList<>();
            Map<Long, CrossStrongholdUserRoungDamage> damageMap = entry.getValue();
            for (CrossStrongholdUserRoungDamage damage : damageMap.values()) {
                if (damage.getUnionId().equals(unionId)) {
                    list.add(damage);
                }
            }
            tempMap.put(round, list);
        }
        return tempMap;
    }


    public BigInteger getUnionScore(String unionId) {
        StrongholdEliminateUnionScore unionScore = unionScoreMap.get(unionId);
        if (unionScore == null) {
            return BigInteger.ZERO;
        }
        return unionScore.getHistoryScore().add(unionScore.getCurRoundScore());
    }

    public int getGroupId() {
        return groupId;
    }
}
